import tkinter as tk
import pymssql
#上级管理部门-发布新养护任务的页面
#publish_maintenance_task_page.py
def open_publish_maintenance_task_page():
    publish_maintenance_task_window = tk.Tk()
    publish_maintenance_task_window.title("上级主管部门-发布养护任务页面")
    publish_maintenance_task_window.geometry("300x500")

    # 提示文本
    label_task_number = tk.Label(publish_maintenance_task_window, text="任务编号：")
    label_task_number.pack(pady=5)

    # 输入框
    entry_task_number = tk.Entry(publish_maintenance_task_window)
    entry_task_number.pack(pady=5)

    # 提示文本
    label_task_name = tk.Label(publish_maintenance_task_window, text="任务名称：")
    label_task_name.pack(pady=5)

    # 输入框
    entry_task_name = tk.Entry(publish_maintenance_task_window)
    entry_task_name.pack(pady=5)

    # 提示文本
    label_executor = tk.Label(publish_maintenance_task_window, text="执行人员：")
    label_executor.pack(pady=5)

    # 输入框
    entry_executor = tk.Entry(publish_maintenance_task_window)
    entry_executor.pack(pady=5)

    # 提示文本
    label_publish_time = tk.Label(publish_maintenance_task_window, text="发布时间：")
    label_publish_time.pack(pady=5)

    # 输入框
    entry_publish_time = tk.Entry(publish_maintenance_task_window)
    entry_publish_time.pack(pady=5)

    # 提示文本
    label_result = tk.Label(publish_maintenance_task_window, text="")
    label_result.pack(pady=5)

    # 发布按钮
    def publish_maintenance_task():
        task_number = entry_task_number.get()
        task_name = entry_task_name.get()
        executor = entry_executor.get()
        publish_time = entry_publish_time.get()

        success = publish_maintenance_task_to_database(task_number, task_name, executor, publish_time)

        if success:
            result_text = "发布成功！"
        else:
            result_text = "发布失败，请检查输入。"

        label_result.config(text=result_text)

    publish_button = tk.Button(publish_maintenance_task_window, text="发布养护任务", command=publish_maintenance_task)
    publish_button.pack(pady=10)

    publish_maintenance_task_window.mainloop()

# 将养护任务信息保存到数据库中
def publish_maintenance_task_to_database(task_number, task_name, executor, publish_time):
    try:
        # 连接到数据库
        conn = pymssql.connect(
            host='localhost',
            user='CSY',
            password='211002624',
            database='植物管理系统',
            as_dict=True
        )
        cursor = conn.cursor()

        # 执行插入语句，任务类型默认为“养护”，任务状态默认为0
        query = f"INSERT INTO 操作 (任务编号, 任务名称, 任务类型, 执行人员, 发布时间, 任务状态) VALUES " \
                f"('{task_number}', '{task_name}', '养护', '{executor}', '{publish_time}', 0)"
        cursor.execute(query)

        # 提交更改
        conn.commit()

        # 关闭数据库连接
        conn.close()

        return True
    except Exception as e:
        print(f"Error: {e}")
        return False
